import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

// ctrl + 左右 是跳过一个单词
// shift + 左右 是选中一个字母
// ctrl + shift + 左右 是选中一个单词
// ctrl + backspace 删除一个单词
// end 跳到行尾
// home 跳到行首
// shift + end 从当前位置选中到行尾
// shift + home 从当前位置选中到行首

// const Register = () => import('@/views/Register')
// ctrl + enter 跳到下一行
// ctrl + shift + enter 跳到上一行
// alt + 上下 挪动代码
// alt + shift + 上下 向上或向下复制一行
const Login = () => import('@/views/Login')
const Detail = () => import('@/views/Detail')
const Layout = () => import('@/views/Layout')
const Article = () => import('@/views/Article')
const Collect = () => import('@/views/Collect')
const Like = () => import('@/views/Like')
const User = () => import('@/views/User')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/article' },
  { path: '/register', component: () => import('@/views/Register') },
  { path: '/login', component: Login },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']
// 导航守卫 => 全局前置守卫
router.beforeEach((to, from, next) => {
  // 执行时机: 每次页面跳转都会触发该函数
  // 只要注册了全局前置守卫, 路由会立即瘫痪, 必须要调用 next() 方法来放行
  // 参数1: to 到哪里去
  // 参数2: from 从哪里来
  // 参数3: next 函数, 决定是否放行, next() 表示放行, next('路径') 表示强制跳转到指定路由, next(false) 表示不放行
  // console.log(to, from)
  // next()

  const token = getToken()
  if (token) {
    next()
  } else {
    // 以后白名单越来越多, 会导致写起来很麻烦
    // if (to.path === '/login' || to.path === '/register' || to.path === '/404') {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('您还未登录, 请登录')
      next('/login')
    }
  }
})
// 后置守卫, 暂时不学
// router.afterEach

export default router
